/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : home.js                                 
*  Description  : 클럽개별메인 
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-06-14  이윤노    Created.  
*  2012-06-14  이윤노    Complete.    
*******************************************************************************/

jQuery(function($){

	//제목
	function clsTitle(){
		this._HTMLDom = null;
		this.errMsg = null;
		this._ERRMSG = {
			"_NOVALUE": "내용을 입력해 주십시요."
		}
				
		this._init();
	}
	
	clsTitle.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content div.club_creat table tbody tr:eq(0) td input");
			this._HTMLDom = {
				"$layer": $layer	
			}
		}
		, setValue: function(val){
			this._HTMLDom["$layer"].val(val);	
		}
		, getValue: function(){
			return this._HTMLDom["$layer"].val();
		}
		, isValid: function(){
			if(this.getValue().trim().length == 0){
				this.errMsg = this._ERRMSG["_NOVALUE"];
				return false;
			}
			return true;
		}
		, getError: function(){
			return this.errMsg;	
		}
	}
	
	//상세내용
	function clsContents(){
		this._HTMLDom =null;
		this.errMsg = null;
		this._ERRMSG = {
			"_NOVALUE": "상세내용을 입력해 주십시요."	
		}	
		this._init();
	}
	
	clsContents.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content div.club_creat table tbody tr:eq(3) td textarea");
			this._HTMLDom = {
				"$layer": $layer	
			}
			$layer.width(700);
		}
		, setValue: function(val){
			this._HTMLDom["$layer"].val(val);
		}
		, getValue: function(){
			return this._HTMLDom["$layer"].val();
		}
		, isValid: function(){
			if(this.getValue().trim()==0){
				this.errMsg = this._ERRMSG["_NOVALUE"];
				return false;	
			}
			return true;	
		}
		, getError: function(){
			return this.errMsg;	
		}
	}	
	
	//공개설정
	function clsOpen(){
		this._HTMLDom = null;
		this.errMsg = null;
		this._ERRMSG = {
			"_NOVALUE": "공개설정을 선택하여 주십시요."	
		}	
		this._init();
	}
	
	clsOpen.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content div.club_creat table tbody tr:eq(4) td input:radio");
			this._HTMLDom = {
				"$layer": $layer	
			}	
			
			$layer.eq(0).prop("checked",true);
		}
		, setValue: function(val){
			this._HTMLDom["$layer"].eq((val=="A"?0:1)).prop("checked",true);
		}
		, getValue: function(){
			var $layer = this._HTMLDom["$layer"];
			var idx = $layer.index($layer.filter(":checked"));
			return (idx?"C":"A");
		}
		, isValid: function(){
			if(this.getValue()<0){
				this.errMsg = this._ERRMSG["_NOVALUE"];
				return false;	
			}
			return true;	
		}
		, getError: function(){
			return this.errMsg;	
		}
	}
	
	//첨부파일
	function clsImgPost(){
		this._HTMLDom = null;
		this.imgList = null;
		this.errMsg = null;
		this._ERRMSG = {
			"_NOVALUE": "공개설정을 선택하여 주십시요."	
		}	
		this._init();
	}
	
	clsImgPost.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content div.club_creat table tbody tr:eq(2) td ul");
			this._HTMLDom = {
				"$layer": $layer	
				, "$element": $layer.find("li:first")
				, "$view": $("div#container section#main_content div.club_creat table tbody tr:eq(1)")
			}
			var thisClass = this;
			this._HTMLDom["$view"].find("input:text").attr("readonly",true);
			
			$layer.empty();
			$layer.hide();
			
			var p = this.$getBtnPost().position();
			
			_gf.setUploadFileImage(this.$getBtnPost(), "50x50", function(ret){
				thisClass.push(ret["파일리스트"][0]);
			},{
				"left": p["left"]
				, "top": p["top"]	-18
			});
			
			this._bind();
		}
		, _bind: function(){
			var $layer = this._HTMLDom["$layer"];
			var thisClass = this;
			
			$layer.on("click", "li img:nth-child(1)", function(){				
				var idx = thisClass.$getBtnCancel().index($(this));
				thisClass.imgList.splice(idx,1);
				$layer.find("li").eq(idx).remove();
			});
		}
		, setValue: function(thisData){
			this.imgList = thisData;
			this.display();
		}
		, getValue: function(){
			var szRet = "";
			
			if(this.imgList){
				for(var i=0;i<this.imgList.length;i++){
					if(szRet) szRet += ",";				
					szRet += this.imgList[i]["키"] + "," + this.imgList[i]["섬네일"] + "," + this.imgList[i]["파일명"] + "," + this.imgList[i]["원본파일명"];
				}			
			}
			
			return szRet;			
		}
		, isValid: function(){
			if(!this.imgList.length){
				this.errMsg = this._ERRMSG["_NOVALUE"];
				return false;	
			}
			return true;	
		}
		, getError: function(){
			return this.errMsg;	
		}
		, display: function(){
			var $layer = this._HTMLDom["$layer"];
			var $element = this._HTMLDom["$element"];
			var thisClass = this;
			
			for(var i=0;i<this.imgList.length;++i){
				$layer.append($element.clone(true));	
			}
			
			$layer.find("li").each(function(n){
				$(this).find("img:eq(0)").attr("src", _gf.filePath2Url(thisClass.imgList[n]["파일경로"] + thisClass.imgList[n]["섬네일"]));		
			});
			
			if(this.imgList.length == 0) $layer.hide()
			else $layer.show();
			
		}	
		, $getBtnPost: function(){
			return this._HTMLDom["$view"].find("a>img");
		}
		, $getBtnCancel: function(){
			return this._HTMLDom["$layer"].find("li img[alt=삭제]");
		}
		, push: function(resData){
			_gf.spinEnd();
			if(!this.imgList) this.imgList = [];
			
			if(!resData["키"]) resData["키"] = "NOT";
			if(!resData["섬네일"]) resData["섬네일"] = "NOT";
			
			this.imgList.push(resData);
			
			this.addThumb(resData);
		}
		, addThumb: function(resData){
			var $layer = this._HTMLDom["$layer"];
			var $element = this._HTMLDom["$element"];
			var $text = this._HTMLDom["$view"].find("input:text");
			
			$layer.append($element.clone(true));
			$layer.find("li:last img:eq(0)").attr("src", _UPLOADURL_TMP+"/"+ resData["섬네일"]);
			$text.val(resData["원본파일명"]);
			if($layer.filter(":hidden")) $layer.show();
		}
	}
		
	function clsComm()
	{
		this.clubBoardView=null;
		this.clubBoardViewRequest=null;
		
	
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){		
			this.clubBoardViewRequest = {
				"동호회키": null
				, "게시판키": null
			}
		}
//------------------------수정글정보조회------------------------//		
		, getClubBoardView: function(){			
			var thisClass = this;
			
			var szBoardSeq = this.clubBoardViewRequest["게시판키"];
				
			// ajax 시작			
			//parameter setting and run
			_gf.ajax({
				"sid":"CB001",
				"servicename":"getDetailClubBoard"
			}, {
				  "board_seq": szBoardSeq
				  , "modpage_yn": "N"
			}, function(ret){
				
				// callback and mapping
				if(ret["msp"]["contents"]["items"]){
										
					var obj = ret["msp"]["contents"]["items"];
					
					var reg_date = obj["reg__date"]+"";
					var reg_time = obj["reg__time"]+"";
					var fileBean = obj["FileBean"];
					
					var aFileList = [];
					
					if(fileBean){
						
						if(!fileBean[0]["items"].length) {
							fileBean[0]["items"] = new Array(fileBean[0]["items"]);	
						}
						for(var i=-0;i<fileBean[0]["items"].length;i++){
							var objFile = fileBean[0]["items"][i];
							aFileList.push({
								"파일키": _util.nvl(objFile["file__seq"])
								, "섬네일": _util.nvl(objFile["thumb"])
								, "파일명": _util.nvl(objFile["path"]) + _util.nvl(objFile["save__file__name"])
								, "파일경로": _util.nvl(objFile["path"])
								, "원본파일명": _util.nvl(objFile["orgn__file__name"])
							});
						}
					}
					
					//게시글상세정보
					thisClass.clubBoardView = {
						"동호회키": _util.nvl(obj["board__seq"])
						, "제목": _util.nvl(obj["title"])
						, "내용": _util.nvl(obj["content"])
						, "공개유무": _util.nvl(obj["view__type"])
						, "공지유무": _util.nvl(obj["notice__yn"])
						, "파일리스트": _util.nvl(aFileList)
					};
					
				}    

				$(thisClass).trigger("evtFinishClubBoardView");
			});
		}
		, getClubBoardViewData: function(){
			return this.clubBoardView;
		}
		, setClubBoardViewRequest: function(key,val){
			this.clubBoardViewRequest[key]=val;	
		}
//------------------------수정글정보조회------------------------//		
//------------------------ 글등록/수정------------------------//		

		, InsertBoardData: function(arg){			
			var thisClass = this;
			
			var szClubSeq = arg["동호회키"];
			var szBoardSeq = arg["게시판키"];
			var szTitle = arg["제목"].replace(/"/g, "\\\"");
			var szContent = arg["내용"].replace(/\n/g,"").replace(/"/g, "\\\"");
			var szViewType = arg["공개유무"];
			var szFile = arg["파일리스트"];			
			var szModule = !arg["게시판키"]?"regClubBoard":"updateClubBoard"
				
			// ajax 시작			
			//parameter setting and run
			_gf.ajax({
				"sid":"CB001",
				"servicename": szModule
			}, {
				"board_type": "P"
				, "club_seq": szClubSeq
				, "board_seq": szBoardSeq
				, "title": szTitle
				, "content": szContent
				, "view_type": szViewType //A : 전체 / C: 동호회
				, "notice_yn": "N"
				, "file_list": szFile 
				, "file_list_attach": ""
			}, function(ret){				
				
				// callback and mapping
				var resData = {
					"응답코드": (ret["msp"]["contents"]["serviceResult"] == "00000"?true:false)
					, "메세지": _gf.getResultMsg(ret)
				}
				
				$(thisClass).trigger("evtFinishClubSubmit", [resData]);				
			});
			// ajax 끝
			
		}
//------------------------ 글등록------------------------//	
	}
	
	function clsControl()
	{
		this.club_seq = null;
		this.club_my = null;
		
		this.objComm = null;
		
		this.objClubInfo = null
		this.objRole = null;
		
		this.objTitle = null;
		this.objContents = null;
		this.objOpen = null;
		this.objImgPost = null;
		
		this._init();
	}
	
	clsControl.prototype = {
		_init: function(){
			var member_id = _util.getCookie("member_id");
			this.club_seq = _util.getParam("club_seq");
			this.club_my = _util.getParam("club_my");
			this.board_seq = _util.getParam("board_seq");
			
			if(!member_id) {
				if(confirm("로그인 후 이용하여 주세요.")){
					_gf.goLogin();						
				}else{
					document.location.href = "../club/club.html";
				}
			}else if(!this.club_seq) {
				document.location.href = "../club/club.html";
			}
			
			this._preload();
			
			this.objComm = new clsComm();
			this.objTitle = new clsTitle();
			this.objContents = new clsContents();
			this.objOpen = new clsOpen();
			this.objImgPost = new clsImgPost();
						
			this._beforeStart();
			this._bind();
		}
		, _preload: function(){
			_gf.spinStart();
		}
		, _beforeStart: function(){
			var thisClass = this;
			this._permitStart = {
				
			}
			
			$.ajax({
				url: "js/self_club_top.js"
				, dataType: "script"
				, async: false
				, success: function(){
					
				}
				, error: function(){
					alert("error");
				}
			});
			
			_util.executeThread(function(){
				for(var k in thisClass._permitStart){
					if(!thisClass._permitStart[k]) return false;
				}
				
				return (_clubControl.getClubInfo().infoData);
			}, function(){				
				_gf.spinEnd();;
				thisClass._start();
			});	
		}
		, _role: function(){
			if(!this.objRole.isMember()){
				alert(this.objRole.getError());
				document.location.href = "home.html?club_seq=" + this.infoData["동호회키"];
			}
		}
		, _start: function(){		
			this.objClubInfo = _clubControl.getClubInfo();
			this.objRole = new clsRole(this.objClubInfo.infoData);
			this._role();
			
			//글정보 받아오기
			if(this.board_seq){
				_gf.spinStart("receiving...");					
				
				//수정글정보 조회
				this.objComm.setClubBoardViewRequest("동호회키", this.club_seq);
				this.objComm.setClubBoardViewRequest("게시판키", this.board_seq);
				this.objComm.getClubBoardView();
			
			}
		}
		, _bind: function(){
			var thisClass = this;
			
			//게시글 등록 완료이벤트
			$(this.objComm).bind("evtFinishClubSubmit", function(event, resData){				
				alert(resData["메세지"]);				
				if(resData["응답코드"]){				
					_gf.spinEnd();					
					document.location.href = "club_picture_list.html" + thisClass.returnParam();
				}			
			});
			
			// 게시글상세정보 조회 완료이벤트
			$(this.objComm).bind("evtFinishClubBoardView", function(){
				
				var thisData = thisClass.objComm.getClubBoardViewData();
				//thisClass.objNote.setValue(thisData);				
				//thisClass.objUploadFile.setList(thisData["파일리스트"]);
								
				thisClass.objTitle.setValue(thisData["제목"]);
				thisClass.objContents.setValue(thisData["내용"]);
				thisClass.objOpen.setValue(thisData["공개유무"]);
				thisClass.objImgPost.setValue(thisData["파일리스트"]);
				
				_gf.spinEnd();
				
			});
			
			//확인
			$("div#container p.btn_center img[alt=확인]").click(function(event){
				var szTitle = thisClass.objTitle.getValue();
				var szContents = thisClass.objContents.getValue();
				var szOpen = thisClass.objOpen.getValue();
				var szImgPost = thisClass.objImgPost.getValue();
		
				var submitData = {
					"동호회키": thisClass.club_seq
					, "게시판키": thisClass.board_seq
					, "제목": szTitle
					, "내용": szContents
					, "공개유무": szOpen
					, "파일리스트": szImgPost
				}
			
				if(!thisClass.objTitle.isValid()){
					alert(thisClass.objTitle.getError());
					return;
				}else if(!thisClass.objContents.isValid()){
					alert(thisClass.objContents.getError());
					return;
				}else if(!thisClass.objOpen.isValid()){
					alert(thisClass.objOpen.getError());
					return;
				}else if(!thisClass.objImgPost.isValid()){
					alert(thisClass.objImgPost.getError());
					return;
				}
				thisClass.objComm.InsertBoardData(submitData);					
				_gf.spinStart("저장중입니다.,.");			
			});
			
			//취소
			$("div#container p.btn_center img[alt=취소]").click(function(event){
				document.location.href = "club_picture_list.html" + thisClass.returnParam();
			});
						
		}
		// 이미지(CKEditer) 업로드
		, finishUploadFile: function(ret){
			//this.objNote.insertImage(ret["파일리스트"][0]["파일명"].replace(_UPLOADPATH_TMP, _UPLOADURL_TMP));
			this.objNote.insertImage(ret["파일리스트"][0]["파일명"].replace(_UPLOADPATH_TMP, _UPLOADURL_TMP));

			this.objUploadFile.push(ret["파일리스트"][0]);
		}
		, returnParam: function(){
			return "?club_seq="  + this.club_seq + "&club_my=" + this.club_my;
		}
	}
	
	document.objControl = new clsControl();
});